package org.example.springcaptchademo.controller;

import cn.hutool.captcha.CaptchaUtil;
import cn.hutool.captcha.LineCaptcha;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import jakarta.servlet.http.HttpSession;
import org.example.springcaptchademo.model.CaptchaProperties;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.io.IOException;

@RequestMapping("/captcha")
@RestController
public class CaptchaController {
    @Autowired
    private CaptchaProperties captchaProperties;
    private static long VILID_MILLIS_TIME=1000*60*5;
    @RequestMapping("/getCaptcha")
    public void getCaptcha(HttpServletRequest request, HttpServletResponse  response) throws IOException {
        HttpSession session = request.getSession();
        //        定义验证码的长和宽
        LineCaptcha linecaptcha= CaptchaUtil.createLineCaptcha(captchaProperties.getWidth(),captchaProperties.getHeight());
        String code=linecaptcha.getCode();
        response.setContentType("image/png");
//        禁止使用缓存
        response.setHeader("Pragma", "No-cache");
        linecaptcha.write(response.getOutputStream());
        System.out.println( code);
        //写到session
        session.setAttribute(captchaProperties.getSession().getCode(),code);
        session.setAttribute(captchaProperties.getSession().getDate(),System.currentTimeMillis());
    }
    @RequestMapping("/check")
    public boolean check(String captcha,HttpSession  session){
        System.out.println("用户输入的验证码:"+captcha);
        if (!StringUtils.hasLength(captcha)){
            return false;
        }
        String code= (String) session.getAttribute(captchaProperties.getSession().getCode());
        long date= (long) session.getAttribute(captchaProperties.getSession().getDate());
        if (code.equals(captcha) && System.currentTimeMillis() - date < VILID_MILLIS_TIME){
            return true;
        }
        return false;
    }
}
